
// 公告模块

const sequelize = require('../config/operateDB');
const {Sequelize, DataTypes, Op} = require('sequelize');


const Notice = sequelize.define('notice', {
    id: {
        type: DataTypes.BIGINT,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true,
    },
    title: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    content: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
}, {

})

Notice.sync();

const noticeModel = {
    async getNotice(ctx) {
        const params = ctx.query;
        // const count = await Notice.count();
        const {offset = 0, limit = 10, keywords = ''} = params;
        const { count, rows } = await Notice.findAndCountAll(
            {
                where: {
                    title: {
                        [Op.like]: '%' + keywords + '%',
                    },
                },
                limit: parseInt(limit),
                offset: parseInt(offset),
                raw: true,
            }
        );

        ctx.pageRes({
            limit,
            offset,
            list: rows,
            total: count,
        });
    },

    async addNotice(ctx) {
        const params = ctx.request.body;
        const validFlag = this.validNotice(ctx, params);
        if (validFlag) {
            const notice = await Notice.create({
                ...params,
            });

            ctx.success('增加成功！', notice);
        }
    },
    validNotice(ctx, params) {
        if (!params.title) {
            ctx.errorParams('公告标题不存在！');
            return false;
        } else if (!params.content) {
            ctx.errorParams('公告内容不存在！');
            return false;
        } else {
            return true;
        }
    },
    async deleteNotice(ctx)  {
        const deleteId = ctx.request.body.id;
        if (!deleteId) {
            ctx.errorParams('id不存在！');
        } else {
            await Notice.destroy({
                where: {
                    id: deleteId,
                }
            });

            ctx.success('删除成功！', {
                id: deleteId,
            })
        }
        
    },
    async editNotice(ctx)  {
        const params = ctx.request.body;
        console.log(params.id);
        const editId = params.id;
        if (!editId) {
            ctx.errorParams('id不存在！');
        } else {
            // 
            const notice = await Notice.findOne({
                where: {
                    id: editId
                },
                raw: true,
            });
            await Notice.update({
                ...notice,
                ...params,
            }, {
                where: {
                    id: editId
                },
            })
            
            ctx.success('修改成功', {
                id: editId,
            });
        }
        
    }
    
};


module.exports = noticeModel;